package de.hs.rm;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

public class BHModeGamepadActivity extends Activity{

	private BHMainApplication mainApp= null;
	private TextView tvValues;
	
	private SensorManager btSensorManager;
	private Sensor btAccSensor;
	private Sensor btMaFSensor;
	
	private float[] accelerometerValues;
	private float[] magneticFieldValues;
	
	private Bitmap[] arrowBitmaps = null;
	
	private boolean leftPressed = false;
	private boolean rightPressed = false;
	private boolean upPressed = false;
	private boolean downPressed = false;
	
	private float lrCallib = 0;
	private float udCallib = -20;
	
	private final float NOMOVE_THRESHOLD = 20;
	
	private ImageView ivUpArrow = null;
	private ImageView ivLeftArrow = null;
	private ImageView ivRightArrow = null;
	private ImageView ivDownArrow = null;
		
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prepareImages();
        Drawable bgImage = getResources().getDrawable(R.drawable.gamepadbackground);
        bgImage.setAlpha(30);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.modegamepad);
        //loading images avoiding memory problems
        
        loadInitialImages();
        
        mainApp = (BHMainApplication)this.getApplicationContext();
        
        tvValues = (TextView)findViewById(R.id.values_tv);
        
        btSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        btAccSensor = btSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        btMaFSensor = btSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    }
    
    private void prepareImages()
    {
    	arrowBitmaps = new Bitmap[8];
    	arrowBitmaps[0] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowupgreen, 200, 200);
    	arrowBitmaps[1] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowupred, 200, 200);
    	arrowBitmaps[2] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowleftgreen, 200, 200);
    	arrowBitmaps[3] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowleftred, 200, 200);
    	arrowBitmaps[4] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowrightgreen, 200, 200);
    	arrowBitmaps[5] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowrightred, 200, 200);
    	arrowBitmaps[6] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowdowngreen, 200, 200);
    	arrowBitmaps[7] = ImageConverter.decodeSampledBitmapFromResource(getResources(), R.drawable.arrowdownred, 200, 200);
    }
    
    private void loadInitialImages() {
    	ivUpArrow = (ImageView)findViewById(R.id.arrowupiv);
    	ivLeftArrow = (ImageView)findViewById(R.id.arrowleftiv);
    	ivRightArrow = (ImageView)findViewById(R.id.arrowrightiv);
    	ivDownArrow = (ImageView)findViewById(R.id.arrowdowniv);
    	
    	setArrowImage(ivUpArrow, 0);
    	setArrowImage(ivLeftArrow, 2);
    	setArrowImage(ivRightArrow, 4);
    	setArrowImage(ivDownArrow, 6);
    	
    	
//    	ivUpArrow.setImageBitmap(
//    		    decodeSampledBitmapFromResource(getResources(), R.drawable.arrowupgreen, 200, 200));
//    	ivLeftArrow.setImageBitmap(
//    		    decodeSampledBitmapFromResource(getResources(), R.drawable.arrowleftgreen, 200, 200));
//    	ivRightArrow.setImageBitmap(
//    		    decodeSampledBitmapFromResource(getResources(), R.drawable.arrowrightgreen, 200, 200));
//    	ivDownArrow.setImageBitmap(
//    		    decodeSampledBitmapFromResource(getResources(), R.drawable.arrowdowngreen, 200, 200));
		
	}
    
    private void setArrowImage(ImageView iv,int arrowImageID)
    {
    	iv.setImageBitmap(arrowBitmaps[arrowImageID]);
		
    }
    
    

	@Override
    public void onResume()
    {
    	super.onResume();
    	btSensorManager.registerListener(accelerometerListener, btAccSensor, SensorManager.SENSOR_DELAY_GAME);
    	btSensorManager.registerListener(magenticFieldListener, btMaFSensor, SensorManager.SENSOR_DELAY_GAME);
    }
    
    @Override
    public void onPause()
    {
    	super.onPause();
    	btSensorManager.unregisterListener(accelerometerListener, btAccSensor);
    	btSensorManager.unregisterListener(magenticFieldListener, btMaFSensor);
    }

	
	
	private final SensorEventListener accelerometerListener = new SensorEventListener()
	{
		@Override
		public void onAccuracyChanged(Sensor arg0, int arg1) {
		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			if(Sensor.TYPE_ACCELEROMETER == event.sensor.getType())
			{
				accelerometerValues = event.values.clone();
				getOrientation();
			}			
		}		
	};
	
	private final SensorEventListener magenticFieldListener = new SensorEventListener()
	{
		@Override
		public void onAccuracyChanged(Sensor arg0, int arg1) {
		}

		@Override
		public void onSensorChanged(SensorEvent event) {
			if(Sensor.TYPE_MAGNETIC_FIELD == event.sensor.getType())
			{
					magneticFieldValues = event.values.clone();
			}			
		}		
	};
	
	private void getOrientation()
	{
		if(accelerometerValues != null 
				&& magneticFieldValues != null)
		{
//			mainApp.sendBTMessage("xmag: " + magneticFieldValues[0]
//					+ "\tymag: " + magneticFieldValues[1]
//					+ "\tzmag: " + magneticFieldValues[2]
//			);
//			mainApp.sendBTMessage("x: " + accelerometerValues[0]
//					+ "\ty: " + accelerometerValues[1]
//					+ "\tz: " + accelerometerValues[2]
//			);
			
			float[] values = new float[3];
			float[] rotationMatrix = new float[16];
			SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerValues, magneticFieldValues);
			SensorManager.getOrientation(rotationMatrix, values);
						
			values[0] = (float)Math.toDegrees(values[0]);
			values[1] = (float)Math.toDegrees(values[1]);
			values[2] = (float)Math.toDegrees(values[2]);
			
//			mainApp.sendBTMessage("x: " + values[0]
//					+ "\ny: " + values[1]
//					+ "\nz: " + values[2]
//			);
			float leftRight = values[1];
			float upDown = values[2];
			
//			if(leftRight > (30 + lrCallib))
//				mainApp.sendBTMessage("gamePad:left:press");
////			else
////				mainApp.sendBTMessage("gamePad:left:release");
//			
//			else if(leftRight < (-30 + lrCallib))
//				mainApp.sendBTMessage("gamePad:right:press");
////			else
////				mainApp.sendBTMessage("gamePad:right:release");
//			
//			if(upDown > (30 + udCallib))
//				mainApp.sendBTMessage("gamePad:up:press");
////			else
////				mainApp.sendBTMessage("gamePad:up:release");
//			
//			else if(upDown < (-30 + udCallib))
//				mainApp.sendBTMessage("gamePad:down:press");
////			else
////				mainApp.sendBTMessage("gamePad:down:release");
			
			if(leftRight > (NOMOVE_THRESHOLD + lrCallib) && !leftPressed)
			{
				mainApp.sendBTMessage("gamePad:left:press");
				leftPressed = true;
				setArrowImage(ivLeftArrow, 3);
			}
			else if(leftRight < (NOMOVE_THRESHOLD + lrCallib) && leftPressed)
			{
				mainApp.sendBTMessage("gamePad:left:release");
				leftPressed = false;
				setArrowImage(ivLeftArrow, 2);
			}
			
			if(leftRight < (-NOMOVE_THRESHOLD + lrCallib) && !rightPressed)
			{
				mainApp.sendBTMessage("gamePad:right:press");
				rightPressed = true;
				setArrowImage(ivRightArrow, 5);
			}
			else if (leftRight > (-NOMOVE_THRESHOLD + lrCallib) && rightPressed)
			{
				mainApp.sendBTMessage("gamePad:right:release");
				rightPressed = false;
				setArrowImage(ivRightArrow, 4);
			}
			
			if(upDown > (NOMOVE_THRESHOLD - udCallib) && !upPressed)
			{
				mainApp.sendBTMessage("gamePad:up:press");
				upPressed = true;
				setArrowImage(ivUpArrow, 1);
			}
			else if(upDown < (NOMOVE_THRESHOLD - udCallib) && upPressed)
			{
				mainApp.sendBTMessage("gamePad:up:release");
				upPressed = false;
				setArrowImage(ivUpArrow, 0);
			}
			
			if(upDown < (-NOMOVE_THRESHOLD + udCallib) && !downPressed)
			{
				mainApp.sendBTMessage("gamePad:down:press");
				downPressed = true;
				setArrowImage(ivDownArrow, 7);
			}
			else if(upDown > (-NOMOVE_THRESHOLD + udCallib) && downPressed)
			{
				mainApp.sendBTMessage("gamePad:down:release");
				downPressed = false;
				setArrowImage(ivDownArrow, 6);
			}

			
			tvValues.setText("x: " + values[0]
				+ "\ny: " + values[1]
				+ "\nz: " + values[2]
			);
		}
	}
}
